package com.jyy.prefabricated.service;


import com.alibaba.excel.EasyExcel;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Image;
import com.jyy.prefabricated.common.AjaxResult;
import com.jyy.prefabricated.dto.*;
import com.jyy.prefabricated.entity.*;
import com.jyy.prefabricated.enums.*;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.listener.EnrollsExcelListener;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.utils.PdfUtils;
import com.jyy.prefabricated.utils.QrCodeUtil;
import com.jyy.prefabricated.utils.UserUtils;
import com.jyy.prefabricated.vo.CerticateVo;
import com.jyy.prefabricated.vo.EnrollsProjectData;
import com.jyy.prefabricated.vo.StudentSignUpApplyVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * @version 1.0.0
 * @author: zjj
 */
@Slf4j
@Service
public class StudentSignUpApplyService {

    @Value("${zkz.ewmUrl}")
    private String ewmUrl;
    @Value("${zkz.ewmPath}")
    private String ewmPath;

    @Resource
    private StudentSignUpApplyMapper applyMapper;

    @Resource
    private ExamPointsMapper examPointsMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private UserUtils userUtils;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private StudentSignUpApplyPhotoMapper studentSignUpApplyPhotoMapper;

    @Resource
    private BosService bosService;

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Resource
    private OfflineOrderMapper offlineOrderMapper;

    @Resource
    private ExamPointsMapper pointsMapper;
    @Resource
    private ExamApplyMapper examApplyMapper;

    @Resource
    private StudentProjectMapper studentProjectMapper;

    @Resource
    private ExamApplyStudentMapper applyStudentMapper;


    // @Transactional(isolation = Isolation.REPEATABLE_READ)
    public int insert(StudentSignUpApply apply) {
        SysUser user = userUtils.getCurrentUser();
        //判断看是否超过考核站点限制人数
        ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(apply.getExamPointId());
        if (examPoints != null) {
            if (examPoints.getInventory() <= 0) {
                return -1;
                // throw new CustomException(403, "当前站点人数已满，请重新选择站点或等待该站点下一期考试");
            }
        }
        //判断该项目，该学员是否超过两年，超过了，不允许报名
        if (!registrationJudge(apply.getProjectId(), apply.getIdCard())) {
            //throw new CustomException(403, "报名该项目已超过2年，不允许再报考");
            return -2;
        }
        StudentDto dto = new StudentDto();
        //当前用户是培训机构
        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
            dto.setTrainingOrganizationId(user.getTrainingOrganization().getId());
            apply.setRegistrationType(RegistrationTypeEnum.TWO.getValue());
            apply.setTrainingOrganizationId(user.getTrainingOrganization().getId());
        } else {
            dto.setTrainingOrganizationId(user.getStudent().getId());
            dto.setTel(user.getUsername());
            apply.setRegistrationType(RegistrationTypeEnum.ONE.getValue());
            apply.setTrainingOrganizationId(user.getStudent().getId());

        }
        dto.setName(apply.getName());
        dto.setIdCard(apply.getIdCard());
        dto.setTel(apply.getTel());
        List<Integer> projectIds = new ArrayList<>();
        projectIds.add(apply.getProjectId());
        dto.setProjectIds(projectIds);
        //给学员注册账号
        int studentId = studentService.insertInfo(dto);
        apply.setStatus(StudentSignUpApplyStatusEnum.ZREO.getValue());
        apply.setStudentId(studentId);
        apply.setPayType(PayTypeEnum.WAIT.getCode());
        apply.setFlag(DeletedEnum.INVALID.getValue());
        applyMapper.insert(apply);

        if (apply.getDiplomaList() != null && apply.getDiplomaList().size() > 0) {

            for (int i = 0; i < apply.getDiplomaList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getDiplomaList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.ONE.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }

        if (apply.getJobTestifyList() != null && apply.getJobTestifyList().size() > 0) {

            for (int i = 0; i < apply.getJobTestifyList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getJobTestifyList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.TWO.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }

        if (apply.getJuniorCertificateList() != null && apply.getJuniorCertificateList().size() > 0) {

            for (int i = 0; i < apply.getJuniorCertificateList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getJuniorCertificateList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.THREE.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }


        return apply.getId();
    }


    public int insert(MultipartFile file, Integer projectId) {

        try {
            List<StudentSignUpApply> studentSignUpApplyList = new ArrayList<>();

            EnrollsExcelListener listener = new EnrollsExcelListener();

            EasyExcel.read(file.getInputStream(), EnrollsProjectData.class, listener).sheet().doRead();
            studentSignUpApplyList = listener.getStudentDList();

            SysUser user = userUtils.getCurrentUser();

            if (studentSignUpApplyList.isEmpty()) {
                //throw new CustomException("导入学员信息为空");
                return -1;
            }
            if (studentSignUpApplyList.size() > 0) {
                for (StudentSignUpApply studentSignUpApply : studentSignUpApplyList) {
                    //判断该项目，该学员是否超过两年，超过了，不允许报名
                    if (!registrationJudge(projectId, studentSignUpApply.getIdCard())) {
                        //throw new CustomException(403, "报名该项目已超过2年，不允许再报考");
                        return -2;
                    } else {
                        StudentDto dto = new StudentDto();
                        //当前用户是培训机构
                        if (UserTypeEnum.TRAININGORGANIZATION.getValue().equals(user.getUserType())) {
                            dto.setTrainingOrganizationId(user.getTrainingOrganization().getId());
                        }

                        if (studentSignUpApply.getName() == null || studentSignUpApply.getName() == ""
                                || studentSignUpApply.getIdCard() == null || studentSignUpApply.getIdCard() == ""
                                || studentSignUpApply.getTel() == null || studentSignUpApply.getTel() == ""
                                || studentSignUpApply.getEducationBackground() == null) {
                            return -3;

                        }
                        dto.setName(studentSignUpApply.getName());
                        dto.setIdCard(studentSignUpApply.getIdCard());
                        dto.setTel(studentSignUpApply.getTel());
                        List<Integer> projectIds = new ArrayList<>();
                        projectIds.add(projectId);
                        dto.setProjectIds(projectIds);
                        //给学员注册账号
                        int studentId = studentService.insertInfo(dto);
                        studentSignUpApply.setStatus(StudentSignUpApplyStatusEnum.ZREO.getValue());
                        studentSignUpApply.setStudentId(studentId);
                        studentSignUpApply.setPayType(PayTypeEnum.WAIT.getCode());
                        studentSignUpApply.setTrainingOrganizationId(user.getTrainingOrganization().getId());
                        studentSignUpApply.setProjectId(projectId);
                        studentSignUpApply.setRegistrationType(RegistrationTypeEnum.TWO.getValue());
                        studentSignUpApply.setFlag(DeletedEnum.INVALID.getValue());
                        applyMapper.insert(studentSignUpApply);
                    }
                }
            }

        } catch (Exception e) {
            throw new CustomException("批量导入失败");
        }


        return 1;
    }

    /**
     * 保存申请和学员的绑定信息
     *
     * @param dto
     * @param id
     */
    public void saveApplyId2Student(ExamApplyDto dto, Integer id) {
        if (dto.getStudentIds().size() > 0) {
            List<ExamApplyStudent> applyStudents = new ArrayList<>();
            for (Integer studentId : dto.getStudentIds()) {
                ExamApplyStudent applyStudent = new ExamApplyStudent();
                applyStudent.setApplyId(id);
                applyStudent.setStudentId(studentId);
                applyStudents.add(applyStudent);
            }
            applyStudentMapper.batchInsert(applyStudents);
        }
    }

    public int update(StudentSignUpApply apply) {
        if (apply.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        StudentSignUpApply studentSignUpApply = applyMapper.selectById(apply.getId());
        ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(apply.getExamPointId());

        //如果修改了考核点
        if (studentSignUpApply.getExamPointId() != null && !studentSignUpApply.getExamPointId().equals(apply.getExamPointId())) {
            //判断看是否超过考核站点限制人数

            if (examPoints != null) {
                if (examPoints.getInventory() <= 0) {
                    //throw new CustomException(403, "当前站点人数已满，请重新选择站点或等待该站点下一期考试");
                    return -1;
                }
            }
        }

        studentSignUpApplyPhotoMapper.deleteByStudentSignUpApplyId(apply.getId());
        if (apply.getDiplomaList() != null && apply.getDiplomaList().size() > 0) {

            for (int i = 0; i < apply.getDiplomaList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getDiplomaList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.ONE.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }

        if (apply.getJobTestifyList() != null && apply.getJobTestifyList().size() > 0) {

            for (int i = 0; i < apply.getJobTestifyList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getJobTestifyList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.TWO.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }

        if (apply.getJuniorCertificateList() != null && apply.getJuniorCertificateList().size() > 0) {

            for (int i = 0; i < apply.getJuniorCertificateList().size(); i++) {
                StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                studentSignUpApplyPhoto.setStudentSignUpApplyId(apply.getId());
                studentSignUpApplyPhoto.setPic(apply.getJuniorCertificateList().get(i));
                studentSignUpApplyPhoto.setPhotoType(StudentSignUpApplyPhotoEnum.THREE.getCode());
                studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
            }

        }

        //审核不通过后，修改后，状态为待审核

        if (studentSignUpApply.getStatus().equals(StudentSignUpApplyStatusEnum.FOUR.getValue())) {
            apply.setStatus(StudentSignUpApplyStatusEnum.THREE.getValue());

        }
        return applyMapper.updateByPrimaryKeySelective(apply);
    }

    /**
     * 审核
     *
     * @param apply
     * @return
     */
    public int updateStatus(StudentSignUpApply apply) {
        if (apply.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        StudentSignUpApplyVo vo = applyMapper.selectByPrimaryKey(apply.getId());
        ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(vo.getExamPointId());

        //报名通过后，分配准考证和机器编号,科目二不分配
        if (apply.getStatus().equals(StudentSignUpApplyStatusEnum.FIVE.getValue()) && !vo.getSubjectType().equals(SubjectStatusEnum.TEO.getValue())) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String sd = "";
            try {
                Date nowTime = vo.getCreateTime();
                // 时间戳转换日期
                sd = sdf.format(nowTime);
            } catch (Exception e) {
                log.debug(e.getMessage());
            }
            Integer t = (int) ((Math.random() * 9 + 1) * 100000);
            //拼接准考证编号

            String admissionTicket = sd + vo.getProjectId().toString() + t;
            apply.setAdmissionTicket(admissionTicket);

            Random random = new Random();

            List<Integer> list = new ArrayList<Integer>();

            StudentSignUpApply dto = new StudentSignUpApply();

            dto.setExamPointId(vo.getExamPointId());
            List<StudentSignUpApply> studentSignUpApplyList = applyMapper.selectByStudentSignUpApply(dto);
            for (StudentSignUpApply studentSignUpApply : studentSignUpApplyList) {
                if (studentSignUpApply.getMachineNumber() != null) {
                    list.add(studentSignUpApply.getMachineNumber());
                }
            }
            int mn = getRandomNumber(examPoints.getMachineCount(), list);
            apply.setMachineNumber(mn);

            //分配考试
            StudentSignUpApply ssa = applyMapper.selectById(apply.getId());
            List<Exam> examList = examMapper.selectByProjectId(ssa.getProjectId());

            if (examList != null && examList.size() > 0) {

                for (Exam exam : examList) {
                    ExamApply examApply = new ExamApply();
                    ExamApplyDto examApplyDto = new ExamApplyDto();

                    examApplyDto.setExamId(exam.getId());
                    List<Integer> studentIds = new ArrayList<>();
                    studentIds.add(ssa.getStudentId());
                    examApplyDto.setStudentIds(studentIds);
                    BeanUtils.copyProperties(examApplyDto, examApply);

                    //审核通过
                    examApply.setStatus(ApplyStatusEnum.SUCCESS.getValue());

                    ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(exam.getProjectId());
                    ExamPoints point = pointsMapper.selectByPrimaryKey(ssa.getExamPointId());

                    examApply.setExamName(exam.getName());

                    if (projectInfo != null) {
                        examApply.setProjectId(projectInfo.getId());
                        examApply.setProjectName(projectInfo.getName());

                    }
                    if (point != null) {
                        examApply.setPointId(point.getId());
                        examApply.setPointAddress(point.getAddress());
                        examApply.setPointName(point.getName());
                    }

                    examApplyMapper.insert(examApply);
                    saveApplyId2Student(examApplyDto, examApply.getId());

                    //批量更新分配状态
                    studentProjectMapper.batchUpdateStatus(examApplyDto.getStudentIds(), exam.getProjectId());
                }
            }
        }

        return applyMapper.updateByPrimaryKeySelective(apply);
    }

    /**
     * 退款接口
     *
     * @param payType     退款申请状态(0未申请 ;1科目一已申请;2科目二已申请;3科目一和科目二已申请)
     * @param id          主键id
     * @param refundAudit 退款审核状态(1科目一已审核;2科目二已审核；3科目一和科目二已审核)
     * @return
     */
    public int updatePayType(Integer payType, Integer id, Integer refundAudit) {
        if (id == null) {
            throw new CustomException("参数id不能为空");
        }
        StudentSignUpApply apply = applyMapper.selectById(id);
        StudentSignUpApply param = new StudentSignUpApply();

        if (payType != null) {
            //查询最早考试时间
            List<Exam> examList = examMapper.selectByProjectId(apply.getProjectId());
            if (examList.size() > 0) {
                //考试前5天内不能退款
                if (dayCompare(examList.get(0).getExamStartTime())) {
                    return -1;
                }
            }
            //退款包含科目一，考核点库存+1
            if (payType.equals(PayTypeEnum.ONE.getCode()) || payType.equals(PayTypeEnum.THREE.getCode())) {

                if (apply.getPayType().equals(PayTypeEnum.WAIT.getCode())) {
                    ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(apply.getExamPointId());
                    examPoints.setInventory(examPoints.getInventory() + 1);
                    examPointsMapper.updateByPrimaryKeySelective(examPoints);
                    param.setIsNull(1);
                    param.setId(apply.getId());
                }


                //提交退款申请后，修改考试申请表状态，学员无法考试
                List<ExamApply> examApplyList = examApplyMapper.selectByprojectIdAndstudentId(apply.getProjectId(), apply.getStudentId());
                if (examApplyList != null && examApplyList.size() > 0) {
                    ExamApply examApply = new ExamApply();
                    examApply.setId(examApplyList.get(0).getId());
                    //考试申请不通过
                    examApply.setStatus(ApplyStatusEnum.FAIL.getValue());
                    examApplyMapper.updateByPrimaryKeySelective(examApply);
                }

            }
            param.setPayType(payType);
        }
        param.setRefundAudit(refundAudit);
        param.setId(id);
        return applyMapper.updateByPrimaryKeySelective(param);
    }


    /**
     * 审核报名项目
     *
     * @param apply
     * @return
     */
    public int updatePayOrder(StudentSignUpApply apply) {
        if (apply.getProjectId() == null || apply.getTrainingOrganizationId() == null) {
            throw new CustomException("项目id和购买人id不能为空");
        }
        return applyMapper.updateByProjectIdAndTrainingOrganizationId(apply);
    }

    /**
     * 通过订单id修改状态
     *
     * @param apply
     * @return
     */
    public int updateByOrderId(StudentSignUpApply apply) {
        if (apply.getOrderId() == null || apply.getStatus() == null) {
            throw new CustomException("订单id和审核状态不能为空");
        }

        //支付凭证不通过,库存加1
        StudentSignUpApply param = new StudentSignUpApply();
        param.setOrderId(apply.getOrderId());
        List<StudentSignUpApply> list = applyMapper.selectByStudentSignUpApply(param);

        if (list != null && list.size() > 0&&apply.getStatus().equals(StudentSignUpApplyStatusEnum.TEO.getValue())) {
            for (StudentSignUpApply t : list) {
                if (t.getSubjectType().equals(SubjectStatusEnum.ONE.getValue()) || t.getSubjectType().equals(SubjectStatusEnum.THREE.getValue())) {
                    ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(t.getExamPointId());
                    examPoints.setInventory(examPoints.getInventory() + 1);
                    examPointsMapper.updateByPrimaryKeySelective(examPoints);
                }
            }
        }


        return applyMapper.updateByOrderId(apply);
    }

    /**
     * 上传支付凭证
     *
     * @param dto
     * @return
     */
    public AjaxResult changePayOrder(PayOrderDto dto) {
        if (dto.getProjectId() == null || dto.getTrainingOrganizationId() == null) {
            throw new CustomException("项目id和购买人id不能为空");
        }
        OfflineOrder offlineOrder = dto.toOfflineOrder();
        offlineOrder.setFlag(DeletedEnum.INVALID.getValue());
        offlineOrderMapper.insert(offlineOrder);
        if (dto.getIds().size() > 0) {
            //分组查询上传支付凭证学员所有考核点
            List<StudentSignUpApply> studentSignUpApplies = applyMapper.selectByIdList(dto.getIds());
            for (StudentSignUpApply examPoint : studentSignUpApplies) {
                ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(examPoint.getExamPointId());
                int kc = examPoints.getInventory();
                StringBuffer studet = new StringBuffer("");
                for (Integer id : dto.getIds()) {
                    StudentSignUpApply ssua = applyMapper.selectById(id);
                    if (!ssua.getSubjectType().equals(SubjectStatusEnum.TEO.getValue()) && ssua.getExamPointId().equals(examPoint.getExamPointId())) {
                        studet.append(ssua.getName() + " ");
                        kc--;
                    }
                }
                if (kc < 0) {
                    return AjaxResult.error(studet + "考核站点机器数不足 请重新选择考核站点");
                }
            }

            //遍历学员查询考核点 根据考核点
            for (Integer id : dto.getIds()) {


                StudentSignUpApply ssua = applyMapper.selectById(id);

                List<StudentSignUpApplyPhoto> studentSignUpApplyPhotoList = studentSignUpApplyPhotoMapper.queryByStudentSignUpApplyId(id);

                if (ssua.getStatus().equals(StudentSignUpApplyStatusEnum.TEO.getValue())) {
                    ssua.setId(null);
                    ssua.setOrderId(offlineOrder.getId());
                    ssua.setStatus(StudentSignUpApplyStatusEnum.ONE.getValue());
                    ssua.setPayOrder(dto.getPayOrder());
                    applyMapper.insert(ssua);

                    for (int i = 0; i < studentSignUpApplyPhotoList.size(); i++) {
                        StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                        studentSignUpApplyPhoto.setStudentSignUpApplyId(ssua.getId());
                        studentSignUpApplyPhoto.setPic(studentSignUpApplyPhotoList.get(i).getPic());
                        studentSignUpApplyPhoto.setPhotoType(studentSignUpApplyPhotoList.get(i).getPhotoType());
                        studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
                    }
                } else {
                    StudentSignUpApply apply = dto.toStudentSignUpApply();
                    apply.setId(id);
                    apply.setOrderId(offlineOrder.getId());
                    apply.setStatus(StudentSignUpApplyStatusEnum.ONE.getValue());
                    applyMapper.updateByPrimaryKeySelective(apply);
                    StudentSignUpApply ap = applyMapper.selectById(id);
                    //支付成功，库存-1;科目一才减去
                    if (!ap.getSubjectType().equals(SubjectStatusEnum.TEO.getValue())) {
                        ExamPoints examPoints = examPointsMapper.selectByPrimaryKey(ap.getExamPointId());
                        examPoints.setInventory(examPoints.getInventory() - 1);
                        examPointsMapper.updateByPrimaryKeySelective(examPoints);
                    }
                }

            }

        }


        return AjaxResult.success();
    }

    /**
     * 补考
     *
     * @param dto
     * @return
     */
    public int makeupExam(MakeUpExamDto dto) {
        if (dto.getProjectId() == null || dto.getTrainingOrganizationId() == null) {
            throw new CustomException("项目id和购买人id不能为空");
        }

        ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(dto.getProjectId());
        if (dto.getIds().size() > 0) {
            for (Integer id : dto.getIds()) {

                StudentSignUpApplyDto ssap = new StudentSignUpApplyDto();
                ssap.setStudentId(id);
                ssap.setCategoryId(projectInfo.getCategoryId());
                List<StudentSignUpApplyVo> list = applyMapper.selectByParam(ssap);
                StudentSignUpApply ssua = new StudentSignUpApply();
                List<StudentSignUpApplyPhoto> studentSignUpApplyPhotoList = studentSignUpApplyPhotoMapper.queryByStudentSignUpApplyId(list.get(0).getId());

                BeanUtils.copyProperties(list.get(0), ssua);
                ssua.setId(null);
                ssua.setOrderId(null);
                ssua.setExamPointId(null);
                ssua.setPayOrder(null);
                ssua.setAdmissionTicket(null);
                ssua.setMachineNumber(null);
                ssua.setOrderId(null);
                ssua.setRefundAudit(null);
                ssua.setSubjectType(null);
                ssua.setStatus(StudentSignUpApplyStatusEnum.ZREO.getValue());
                ssua.setProjectId(dto.getProjectId());
                ssua.setPayType(PayTypeEnum.WAIT.getCode());
                ssua.setTrainingOrganizationId(dto.getTrainingOrganizationId());
                ssua.setRegistrationType(dto.getRegistrationType());

                applyMapper.insert(ssua);

                for (int i = 0; i < studentSignUpApplyPhotoList.size(); i++) {
                    StudentSignUpApplyPhoto studentSignUpApplyPhoto = new StudentSignUpApplyPhoto();
                    studentSignUpApplyPhoto.setStudentSignUpApplyId(ssua.getId());
                    studentSignUpApplyPhoto.setPic(studentSignUpApplyPhotoList.get(i).getPic());
                    studentSignUpApplyPhoto.setPhotoType(studentSignUpApplyPhotoList.get(i).getPhotoType());
                    studentSignUpApplyPhotoMapper.insert(studentSignUpApplyPhoto);
                }
            }
        }
        return 0;
    }


    /**
     * 准考证打印
     *
     * @param id
     * @return
     */
    public void downloadCerticate(HttpServletResponse response, Integer id) {
        StudentSignUpApplyVo studentSignUpApplyVo = applyMapper.selectByPrimaryKey(id);
        Map<String, String> dataMap = new HashMap<>();
        StudentSignUpApplyVo result = applyMapper.selectByPrimaryKey(id);
        String time = "";
        if (result.getProjectId() != null) {
            List<Exam> examList = examMapper.selectByProjectId(result.getProjectId());
            if (examList.size() > 0) {
                time = examList.get(0).getExamStartTime() + " - " + examList.get(0).getExamEndTime();
            }
        }
        if (studentSignUpApplyVo != null) {
            dataMap.put("name", studentSignUpApplyVo.getProjectName());
            dataMap.put("time", time);
            String address = studentSignUpApplyVo.getProvince() + studentSignUpApplyVo.getCity() + studentSignUpApplyVo.getAddress();
            dataMap.put("address", address);
            dataMap.put("machineNumber", studentSignUpApplyVo.getMachineNumber().toString());
            dataMap.put("admissionTicket", studentSignUpApplyVo.getAdmissionTicket());
        }
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/PDF;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + "准考证" + ".pdf");
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        Map<String, Object> o = new HashMap();
        o.put("datemap", dataMap);
        File file = getFileByUrl(studentSignUpApplyVo.getPhoto());
        try {
            // 将文件转化为pdf图片
            Map<String, Image> imgMap = new HashMap();
            Image ewmImage = Image.getInstance(PdfUtils.inputstream2Bytes(PdfUtils.file2InputStream(file)));
            imgMap.put("ewmImg", ewmImage);
            o.put("certificatemap", imgMap);


            //将文件转化为pdf图片(二维码)
            Map<String, Image> imgMapTwo = new HashMap();
            File qrFile = QrCodeUtil.createQrCode(ewmUrl + studentSignUpApplyVo.getAdmissionTicket(), ewmPath, studentSignUpApplyVo.getAdmissionTicket());
            Image ewmImageTwo = Image.getInstance(PdfUtils.inputstream2Bytes(PdfUtils.file2InputStream(qrFile)));
            imgMapTwo.put("ewmImageTwo", ewmImageTwo);
            o.put("imgmap", imgMapTwo);

            ServletOutputStream out = response.getOutputStream();

            PdfUtils.generatePdfByTemplate(o, out, "templates/certificate.pdf");
            qrFile.delete();
        } catch (IOException | BadElementException e) {
            log.debug(e.getMessage());
        } finally {
            file.delete();
        }
    }

    /**
     * 准考证打印
     *
     * @param id
     * @return
     */
    public CerticateVo queryCerticate(Integer id) {

        CerticateVo certicateVo = new CerticateVo();
        StudentSignUpApplyVo studentSignUpApplyVo = applyMapper.selectByPrimaryKey(id);
        StudentSignUpApplyVo result = applyMapper.selectByPrimaryKey(id);
        String time = "";
        if (result.getProjectId() != null) {
            List<Exam> examList = examMapper.selectByProjectId(result.getProjectId());
            if (examList.size() > 0) {
                time = examList.get(0).getExamStartTime() + " - " + examList.get(0).getExamEndTime();
            }
        }

        if (studentSignUpApplyVo != null) {
            certicateVo.setProjectName(studentSignUpApplyVo.getProjectName());
            certicateVo.setTime(time);
            certicateVo.setAddress(studentSignUpApplyVo.getProvince() + studentSignUpApplyVo.getCity() + studentSignUpApplyVo.getAddress());
            certicateVo.setMachineNumber(studentSignUpApplyVo.getMachineNumber());
            certicateVo.setAdmissionTicket(studentSignUpApplyVo.getAdmissionTicket());
            certicateVo.setPhoto(studentSignUpApplyVo.getPhoto());

//            try {
//                File qrFile = QrCodeUtil.createQrCode(ewmUrl + studentSignUpApplyVo.getAdmissionTicket(), ewmPath, studentSignUpApplyVo.getAdmissionTicket());
//                Image ewmImageTwo = Image.getInstance(PdfUtils.inputstream2Bytes(PdfUtils.file2InputStream(qrFile)));
//
//                //file转MultipartFile
//                FileInputStream input = new FileInputStream(qrFile);
//                MultipartFile multipartFile = new MockMultipartFile("file", qrFile.getName(), "text/plain", IOUtils.toByteArray(input));
//                String url = bosService.putObject(multipartFile, "二维码.jpg");
//                certicateVo.setQrUrl(url);
//            } catch (IOException | BadElementException e) {
//                e.printStackTrace();
//            }
        }
        return certicateVo;
    }

    /**
     * 根据准考证编号查询准考证信息
     *
     * @param id
     * @return
     */
    public CerticateVo queryByAdmissionTicket(String id) {
        CerticateVo certicateVo = new CerticateVo();
        StudentSignUpApply studentSignUpApply = applyMapper.selectByAdmissionTicket(id);
        if (studentSignUpApply == null) {
            return certicateVo;
        }
        certicateVo = queryCerticate(studentSignUpApply.getId());
        return certicateVo;
    }


    public int delete(Integer id) {
        StudentSignUpApply studentSignUpApply = new StudentSignUpApply();
        studentSignUpApply.setId(id);
        studentSignUpApply.setFlag(DeletedEnum.VALID.getValue());
        return applyMapper.updateByPrimaryKeySelective(studentSignUpApply);
    }

    public StudentSignUpApplyVo selectById(Integer id) {

        StudentSignUpApplyVo result = applyMapper.selectByPrimaryKey(id);

        List<StudentSignUpApplyPhoto> studentSignUpApplyPhotoList = studentSignUpApplyPhotoMapper.queryByStudentSignUpApplyId(id);

        if (studentSignUpApplyPhotoList.size() > 0) {
            for (int i = 0; i < studentSignUpApplyPhotoList.size(); i++) {
                if (studentSignUpApplyPhotoList.get(i).getPhotoType().equals(StudentSignUpApplyPhotoEnum.ONE.getCode())) {
                    if (result.getDiplomaList() != null) {
                        result.getDiplomaList().add(studentSignUpApplyPhotoList.get(i).getPic());

                    }
                } else if (studentSignUpApplyPhotoList.get(i).getPhotoType().equals(StudentSignUpApplyPhotoEnum.TWO.getCode())) {
                    if (result.getJobTestifyList() != null) {
                        result.getJobTestifyList().add(studentSignUpApplyPhotoList.get(i).getPic());
                    }

                } else {
                    if (result.getJuniorCertificateList() != null) {
                        result.getJuniorCertificateList().add(studentSignUpApplyPhotoList.get(i).getPic());
                    }
                }
            }

        }
        return result;
    }

    public List<StudentSignUpApplyVo> selectByParams(StudentSignUpApplyDto dto) {

        List<StudentSignUpApplyVo> studentSignUpApplyVos = applyMapper.selectByParam(dto);


        if (studentSignUpApplyVos != null && studentSignUpApplyVos.size() > 0) {

            for (StudentSignUpApplyVo studentSignUpApplyVo : studentSignUpApplyVos) {

                if (RefundAuditEnum.ONE.getCode().equals(studentSignUpApplyVo.getRefundAudit()) || RefundAuditEnum.THREE.getCode().equals(studentSignUpApplyVo.getRefundAudit())) {
                    studentSignUpApplyVo.setOneRefund(RefundEnum.THREE.getCode());
                } else if (studentSignUpApplyVo.getPayType().equals(PayTypeEnum.ONE.getCode()) || studentSignUpApplyVo.getPayType().equals(PayTypeEnum.THREE.getCode())) {
                    studentSignUpApplyVo.setOneRefund(RefundEnum.TWO.getCode());
                } else {
                    studentSignUpApplyVo.setOneRefund(RefundEnum.ONE.getCode());
                }
                if (RefundAuditEnum.TWO.getCode().equals(studentSignUpApplyVo.getRefundAudit()) || RefundAuditEnum.THREE.getCode().equals(studentSignUpApplyVo.getRefundAudit())) {
                    studentSignUpApplyVo.setTwoRefund(RefundEnum.THREE.getCode());
                } else if (studentSignUpApplyVo.getPayType().equals(PayTypeEnum.TWO.getCode()) || studentSignUpApplyVo.getPayType().equals(PayTypeEnum.THREE.getCode())) {
                    studentSignUpApplyVo.setTwoRefund(RefundEnum.TWO.getCode());
                } else {
                    studentSignUpApplyVo.setTwoRefund(RefundEnum.ONE.getCode());
                }

                ProjectInfo projectInfo = projectInfoMapper.selectByPrimaryKey(studentSignUpApplyVo.getProjectId());
                if (studentSignUpApplyVo.getRegistrationType().equals(RegistrationTypeEnum.ONE.getValue())) {
                    studentSignUpApplyVo.setTrainingOrganizationName(studentSignUpApplyVo.getName());
                }
                if (studentSignUpApplyVo.getSubjectType() != null) {
                    if (studentSignUpApplyVo.getSubjectType().equals(SubjectStatusEnum.ONE.getValue())) {
                        studentSignUpApplyVo.setCost(projectInfo.getOnePrice());
                    }
                    if (studentSignUpApplyVo.getSubjectType().equals(SubjectStatusEnum.TEO.getValue())) {
                        studentSignUpApplyVo.setCost(projectInfo.getTwoPrice());
                    }
                    if (studentSignUpApplyVo.getSubjectType().equals(SubjectStatusEnum.THREE.getValue())) {
                        studentSignUpApplyVo.setCost(projectInfo.getOnePrice().add(projectInfo.getTwoPrice()));
                    }

                }

            }
        }
        return studentSignUpApplyVos;
    }


    //判断第一次报名该项目至今是否超过2年，超过不允许再报名
    public Boolean registrationJudge(Integer projectId, String idCard) {
        StudentSignUpApply studentSignUpApply = new StudentSignUpApply();
        studentSignUpApply.setProjectId(projectId);
        studentSignUpApply.setIdCard(idCard);
        studentSignUpApply.setStatus(StudentSignUpApplyStatusEnum.FIVE.getValue());
        List<StudentSignUpApply> list = applyMapper.selectByStudentSignUpApply(studentSignUpApply);
        if (list.size() == 0) {
            return true;
        } else {
            Date createTime = list.get(0).getCreateTime();
            String pattern = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            if (yearCompare(simpleDateFormat.format(createTime)) == true) {
                return false;
            }
        }
        return true;
    }

    //判断时间
    public Boolean yearCompare(String oldTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date nowDate = new Date();
        String nowDateStr = sdf.format(nowDate);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime from = LocalDateTime.parse(oldTime, formatter);
        LocalDateTime to = LocalDateTime.parse(nowDateStr, formatter);

        long years = ChronoUnit.YEARS.between(from, to);  // 0 weeks
        System.out.println(years);
        if (years >= 2) {
            return true;
        } else {
            return false;
        }
    }

    //判断时间
    public Boolean dayCompare(String oldTime) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date nowDate = new Date();
        String nowDateStr = sdf.format(nowDate);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime to = LocalDateTime.parse(oldTime, formatter);
        LocalDateTime from = LocalDateTime.parse(nowDateStr, formatter);

        long days = ChronoUnit.DAYS.between(from, to);
        System.out.println(days);
        if (days <= 5) {
            return true;
        } else {
            return false;
        }
    }

    //url转file
    private File getFileByUrl(String fileUrl) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            file = File.createTempFile("file", ".png");
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());
        } catch (Exception e) {
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (stream != null) {
                    stream.close();
                }
                outStream.close();
            } catch (Exception e) {
            }
        }
        return file;
    }

    /**
     * 分配机器编号
     *
     * @param machineCount 机器数量
     * @param list         //已经存在的机器编号集合
     * @return
     */
    public int getRandomNumber(Integer machineCount, List<Integer> list) {

        Integer randomNumber = (int) (Math.random() * machineCount) + 1;//产生[1-machineCount]随机数

        if (!list.contains(randomNumber)) {//判断是否重复，不是重复直接返回
            return randomNumber;
        } else {//如果产生的随机数是重复的，用递归的方法再次生成
            return getRandomNumber(machineCount, list);
        }
    }

}
